<template>
  <view class="container" @click="handleCloseClick">
    <block v-if="isLoading">
      <u-skeleton rows="20" title :loading="isLoading"></u-skeleton>
    </block>
    <block v-if="!isLoading">
      <Header
       ref="header"
        :isFirstPage="isFirstPage"
        :voteId="formData.voteId"
        :communityId="formData.communityId"
        :recordId="isVotingInfo.recordId"
        :VotingratioInfo="VotingratioInfo"
        :isVotingInfo="isVotingInfo"
        :scrollTop="scrollTop"
        :voteTitle="voteInfo.voteTitle"
         :voteContent="voteInfo.voteContent"
         :remark="voteInfo.remark"
      />
      <view class="content-section">
        <view class="content-box-item">
          <VoteCard
            :formData="formData"
            :voteContent="voteInfo.voteContent"
            :isVotingInfo="isVotingInfo"
            :VotingratioInfo="VotingratioInfo"
          />
          <VoteFrom
            ref="voteFrom"
            :isVotingInfo="isVotingInfo"
            :optionInfo="optionInfo"
            v-model="formData.optionId"
            :voteOptions="pmsVoteOptions"
            :voteOptionMap="pmsVoteOptionMap"
            :isRevote="isRevote"
            :mobile="voteInfo.mobile"
          />
          
          <ChooseAHouse
            ref="chooseAHouse"
            :isVotingInfo="isVotingInfo"
            v-if="houseList && houseList.length > 0 && isChooseAHouse"
            :houseList="houseList"
            :voteId="formData.voteId"
            :communityId="formData.communityId"
            :isRevote="isRevote"
            :votedHouseIds="votedHouseIds"
            :houseCheckResult="houseCheckResult"
            :isFromRelatedHouses="isFromRelatedHouses"
            @confirm="selectHouse"
             :mobile="voteInfo.mobile"  
             :initiator="voteInfo.initiator"
          />
          <bloack v-if="!houseList || houseList.length === 0">
            <NotBinding/> 
          </bloack>
             <!-- 添加相关附件组件 -->
      
          <block v-if="houseList && houseList.length > 0">
 

            <block v-if="!isAllHousesVoted()">
          <Signature
            :isVotingInfo="isVotingInfo"
            title="3、签名确定"
            v-if="isSignature"
            @uploadSign="uploadSign"
            @goToSign="goToSign"
          />
          <Relatedaccessories 
            :fileUrl="voteInfo.fileUrl"
          />
        </block>
          </block>
        </view>
      </view>

      <BottomCard
       :type="options.type"
        :isVotingInfo="isVotingInfo"
        @click="handleClick"
        :isClick="isClick"
        :voteInfo="voteInfo"
        :isCode="true"
        :isRevote="isRevote"
        :voteButtonText="voteButtonText"
         @code="handleCode"
      />
    </block>
      <VoteSuccessModal 
      ref="voteSuccessModal"
      :voteName="voteInfo.voteTitle"
      @close="onVoteSuccessClose"
    />
  </view>
</template>

<script>
import VoteMixin from '@/mixins/VoteMixin'
import Header from './components/Header.vue'
import VoteCard from './components/VoteFromCard.vue'
import VoteFrom from './components/VoteFrom.vue'
import ChooseAHouse from './components/ChooseAHouse.vue'
import BottomCard from '@/components/BottomCard/index.vue'
import Signature from '@/components/Signature/index.vue'
import VoteSuccessModal from '@/components/VoteSuccessModal/index.vue'
import NotBinding from '@/components/NotBinding/index.vue'
import Relatedaccessories from './components/Relatedaccessories.vue' // 导入相关附件组件
import { mapActions } from 'vuex'

export default {
  name: 'VotingFormPage',
  mixins: [VoteMixin],
  components: {
    Header,
    VoteCard,
    VoteFrom,
    ChooseAHouse,
    BottomCard,
    Signature,
    VoteSuccessModal,
    NotBinding,
    Relatedaccessories // 注册组件
  },

  computed: {
    // 计算投票按钮文字
    voteButtonText() {
      // 如果所有房屋都已投票
      if (this.isAllHousesVoted()) {
        return '已完成投票'
      }
      // 如果是重新投票状态（部分房屋已投票，添加了新房屋）
      if (this.isRevote) {
        return '补充投票'
      }
      // 默认情况
      return '投票'
    }
  },

  methods: {
    ...mapActions("community", ["checkLoginAndBoundHouses"]),
    
    onPullDownRefresh() {
      this.init(this.options)
      uni.stopPullDownRefresh()
    },
    
    handleCode(){
      const {voteId,communityId}=this.formData
      uni.navigateTo({
        url: '/pages/votingresultslist/index?voteId=' + voteId + '&communityId=' + communityId
      })
  
    },
  
    // 重写updateIsClick方法以适应votingForm页面的特殊逻辑
    updateIsClick() {
      let fromdata = this.formData
      
      // 检查是否所有房屋都已投票
      if (this.isAllHousesVoted()) {
        this.isClick = false
        return
      }
      
      // 基础条件检查：房屋选择和签名
      // if (!fromdata.houseId || !fromdata.voteSign) {
      //   this.isClick = false
      //   return
      // }

      if (!fromdata.voteSign) {
        this.isClick = false
        return
      }
      
      // 检查选项选择
      let hasValidOptions = false
     
      // 多议题模式：检查每个议题是否都有选择且符合min/max限制
      console.log("this.$refs.voteFrom.groupedOptions",this.$refs.voteFrom.groupedOptions)
      if (this.$refs.voteFrom && this.$refs.voteFrom.groupedOptions && Object.keys(this.$refs.voteFrom.groupedOptions).length > 0) {
        hasValidOptions = this.checkAllQuestionsSelectedWithLimits()
      } 
      // 单议题模式：检查是否有选项选择
      else if (Array.isArray(fromdata.optionId) && fromdata.optionId.length > 0) {
        hasValidOptions = true
      }
      
      this.isClick = hasValidOptions
    },
    
    // 检查是否所有房屋都已投票
    isAllHousesVoted() {
      // 判断是否需要进行判定
      // 1. 未投票状态
      // 2. 从关联房屋页面返回
      const shouldCheck = !this.isVotingInfo.isVoting || this.isFromRelatedHouses
      
      if (!shouldCheck) {
        return false
      }
      
      // 如果没有房屋列表，返回 false
      if (!this.houseList || this.houseList.length === 0) {
        return false
      }
      
      // 如果没有检查结果，返回 false
      if (!this.houseCheckResult || !this.houseCheckResult.failedHouse) {
        return false
      }
      
      // 获取所有房屋ID
      const allHouseIds = this.houseList.map(house => String(house.houseId))
      
      // 获取已投票的房屋ID
      const votedHouseIds = this.houseCheckResult.failedHouse.map(item => 
        String(item.pmsHouse?.houseId)
      ).filter(id => id) // 过滤掉 undefined
      
      console.log('检查是否所有房屋都已投票:', {
        allHouseIds,
        votedHouseIds,
        allCount: allHouseIds.length,
        votedCount: votedHouseIds.length,
        isVoting: this.isVotingInfo.isVoting
      })
      
      // 如果所有房屋都已投票，返回 true
      const allVoted = allHouseIds.every(houseId => 
        votedHouseIds.includes(houseId)
      )
      
      return allVoted
    },
    
    // 检查所有议题是否都有选择
    checkAllQuestionsSelected() {
      if (!this.$refs.voteFrom || !this.$refs.voteFrom.groupedOptions || Object.keys(this.$refs.voteFrom.groupedOptions).length === 0) {
        return false
      }
      
      // 获取当前选中的选项
      let selectedOptions = []
      if (this.$refs.voteFrom && this.$refs.voteFrom.getSelectedIndex) {
        selectedOptions = this.$refs.voteFrom.getSelectedIndex()
      }
      
      if (!Array.isArray(selectedOptions) || selectedOptions.length === 0) {
        return false
      }
      
      // 检查每个议题是否都有选择
      const groupedOptions = this.$refs.voteFrom.groupedOptions
      const questionTitles = Object.keys(groupedOptions)
      
      for (let questionTitle of questionTitles) {
        const questionOptions = groupedOptions[questionTitle] || []
        const questionOptionIds = questionOptions.map(option => String(option.optionId))
        
        // 检查当前议题是否有选中的选项
        const hasSelectionForThisQuestion = selectedOptions.some(selectedOption => 
          questionOptionIds.includes(String(selectedOption.optionId))
        )
        
        if (!hasSelectionForThisQuestion) {
          return false
        }
      }
      
      return true
    },
    getQuestionSelectType(questionTitle) {
            const optionMap = this.voteOptionMap && Object.keys(this.voteOptionMap).length > 0 ? 
                this.voteOptionMap : (this.$refs.voteFrom && this.$refs.voteFrom.groupedOptions) || {}
            
            const options = optionMap[questionTitle] || []  
            
            // 检查所有选项的optionType
            const optionTypes = options.map(item => item.optionType).filter(type => type !== null && type !== undefined)
            
            if (optionTypes.length > 0) {
                // 如果所有选项的optionType都相同，使用该类型
                const uniqueTypes = [...new Set(optionTypes)]
                if (uniqueTypes.length === 1) {
                    return uniqueTypes[0] === 2 // 2为多选，1为单选
                }
            }
            
            // 如果optionType都为null或不存在，回退到voteRule
            return this.optionInfo.voteRule == 2 || this.optionInfo.voteRule == 4
        },

    // 检查所有议题是否都有选择且符合min/max限制
    checkAllQuestionsSelectedWithLimits() {
      if (!this.$refs.voteFrom || !this.$refs.voteFrom.groupedOptions || Object.keys(this.$refs.voteFrom.groupedOptions).length === 0) {
        return false
      }
      
      // 获取当前选中的选项
      let selectedOptions = []
      if (this.$refs.voteFrom && this.$refs.voteFrom.getSelectedIndex) {
        selectedOptions = this.$refs.voteFrom.getSelectedIndex()
      }
      
      if (!Array.isArray(selectedOptions)) {
        return false
      }
      
      // 检查每个议题是否都有选择且符合min/max限制
      const groupedOptions = this.$refs.voteFrom.groupedOptions
      const questionTitles = Object.keys(groupedOptions)
      
      for (let questionTitle of questionTitles) {
        const questionOptions = groupedOptions[questionTitle] || []
        const questionOptionIds = questionOptions.map(option => String(option.optionId))
        
        // 计算当前议题的选中选项数量
        const currentQuestionSelectedCount = selectedOptions.filter(selectedOption => 
          questionOptionIds.includes(String(selectedOption.optionId))
        ).length
        
        // 判断是否为多选模式
        const isMultiSelect = this.getQuestionSelectType(questionTitle)
        
        // 如果是多选模式，才进行min/max限制检查
        if (isMultiSelect) {
          // 获取该议题的选择限制
          const questionLimit = this.getQuestionSelectionLimit(questionTitle)
          
          // 多选问题最基础的限制：至少选择1个
          const minRequired = Math.max(questionLimit.min, 1)
          
          console.log('多选验证调试:', {
            questionTitle,
            currentQuestionSelectedCount,
            questionLimit,
            minRequired,
            isMultiSelect
          })
          
          // 检查是否符合min/max限制
          if (currentQuestionSelectedCount < minRequired || currentQuestionSelectedCount > questionLimit.max) {
            console.log('验证失败:', {
              questionTitle,
              current: currentQuestionSelectedCount,
              min: minRequired,
              max: questionLimit.max
            })
            return false
          }
        } else {
          // 单选模式：只检查是否至少选择了一个选项
          if (currentQuestionSelectedCount === 0) {
            return false
          }
        }
      }
      
      return true
    },

    // 获取议题的选择限制（min/max）
    getQuestionSelectionLimit(questionTitle) {
      // 优先从 VoteFrom 组件的 groupedOptions 中获取（包含 mock 数据）
      if (this.$refs.voteFrom && this.$refs.voteFrom.groupedOptions && this.$refs.voteFrom.groupedOptions[questionTitle]) {
        const options = this.$refs.voteFrom.groupedOptions[questionTitle]
        if (options && options.length > 0) {
          // 取第一个选项的 min/max 值（同一议题的所有选项应该有相同的限制）
          const firstOption = options[0]
          return {
            min: firstOption.min || 0,
            max: firstOption.max || 999
          }
        }
      }
      
      // 回退到 pmsVoteOptions
      if (this.pmsVoteOptions && this.pmsVoteOptions.length > 0) {
        const questionOption = this.pmsVoteOptions.find(option => 
          option.title === questionTitle || option.questionTitle === questionTitle
        )
        
        if (questionOption) {
          return {
            min: questionOption.min || 0,
            max: questionOption.max || 999
          }
        }
      }
      
      return { min: 0, max: 999 }
    },
    handleCloseClick(){
      this.$refs.header.handleCloseClick()
    },

    // 重写handleClick方法以适应votingForm页面的特殊逻辑
    handleClick() {
      // 检查是否所有房屋都已投票
      if (this.isAllHousesVoted()) {
        uni.showToast({
          title: '所有房屋均已投票',
          icon: 'none'
        })
        return
      }
      
      // 防止重复提交
      if (this.isSubmitting) {
        console.log("放练级")
        return
      }
      
      this.isSubmitting = true
      
      let fromdata = JSON.parse(JSON.stringify(this.formData))
      fromdata.optionList = this.formData.optionId
      fromdata.optionId = undefined
      fromdata.voteId = Number(fromdata.voteId)
      console.log('this.houseList',this.houseList)
      
      // 获取所有房屋ID
      let houseIds = this.houseList.map(item => item.houseId)
 
      
      // 获取已投票的房屋ID（从 houseCheckResult.failedHouse 中提取）
      const votedHouseIds = []
      if (this.houseCheckResult && this.houseCheckResult.failedHouse) {
        this.houseCheckResult.failedHouse.forEach(item => {
          if (item.pmsHouse && item.pmsHouse.houseId) {
            votedHouseIds.push(String(item.pmsHouse.houseId))
          }
        })
      }
      console.log('已投票的房屋ID:', votedHouseIds)
      
      // 过滤掉已投票的房屋（无论是否有已投票房屋，都执行过滤）
      houseIds = houseIds.filter(houseId => 
        !votedHouseIds.includes(String(houseId))
      )
      console.log('过滤后的房屋ID:', houseIds)
      
      // 检查是否还有未投票的房屋
      if (houseIds.length === 0) {
        this.isSubmitting = false
        uni.showToast({
          title: '所有房屋均已投票',
          icon: 'none'
        })
        return
      }
      
      console.log('最终提交的房屋IDs:', houseIds.join(','))
      fromdata.houseId = houseIds.join(',')
      console.log('fromdata',fromdata)
      // this.formData.houseId = ""

      // this.formData.voteSign = ""
      // this.formData.optionId = ""

      // 调用mixin中的handleVoteAdd方法
      // return
      this.handleVoteAdd(fromdata,2).finally(() => {
        // 无论成功还是失败，都要重置提交状态
        this.isSubmitting = false
      })
    },

    // 重写setIsVotingInfo方法来处理votingForm页面的特殊逻辑
    setIsVotingInfo(row) {
      this.isVotingInfo.recordId = row.recordId
      
      let voteOptionIds = JSON.parse(row.voteOptionId)
      // 统一处理为数组格式，方便VoteFrom组件处理
      this.isVotingInfo.optionId = voteOptionIds
      this.isVotingInfo.isVoting = true
      this.isVotingInfo.voteId = row.voteId
      this.isVotingInfo.houseId = row.houseId
      this.isVotingInfo.createDate = row.createDate
      this.isVotingInfo.voteSign = row.voteSign
    },

    // 重写handleOptionSelection方法来处理votingForm页面的特殊逻辑
    handleOptionSelection() {
      if (this.$refs.voteFrom && this.$refs.voteFrom.getSelectedIndex) {
        let indx = this.$refs.voteFrom.getSelectedIndex()
        if (indx.length >= 0) {
          this.formData.optionId = indx
        }
      }
    },

    // 重写handleAdditionalData方法来处理votingForm页面特有的数据
    handleAdditionalData(data) {
      // 处理voteOptionMap数据，如果存在的话
      if (data.pmsVoteOptionMap) {
        this.pmsVoteOptionMap = data.pmsVoteOptionMap
      } else {
        // 如果没有pmsVoteOptionMap数据，初始化为空对象
        this.pmsVoteOptionMap = {}
      }
    }
  },

  onShareAppMessage(res) {
     return this.share()
  }
}
</script>

<style lang="scss">
page {
  width: 100%;
  height: 100%;
}
.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.content-section {
  width: 100%;
  background: #F5F7FB;
  border-radius: 20rpx;
  padding: 30rpx;
  padding-bottom: 230rpx;
  margin-top: -6px;
}
</style> 